package com.joysuch.wwyt.api.saferisk;


import com.alibaba.fastjson.JSON;
import com.google.gson.JsonObject;

import com.joysuch.wwyt.api.mh.rest.MhMonitPointRestSender;
import com.joysuch.wwyt.api.mh.socket.MhMonitPointSocketSender;
import com.joysuch.wwyt.api.saferisk.bean.APILoginBean;
import com.joysuch.wwyt.api.saferisk.bean.APIResponseBean;
import com.joysuch.wwyt.api.sync.SyncConstants;
import com.joysuch.wwyt.bp.bean.risk.BpTeamSpecialBean;
import com.joysuch.wwyt.bp.entity.risk.BpCompany;
import com.joysuch.wwyt.bp.enums.SafetyRiskWorkTypes;
import com.joysuch.wwyt.bp.repository.BpEnterpriseInfoDao;
import com.joysuch.wwyt.bp.service.BpRiskCompanyService;
import com.joysuch.wwyt.bp.service.BpRiskPromiseBraodcastService;
import com.joysuch.wwyt.core.common.util.SimpleDateFormatCache;
import com.joysuch.wwyt.core.entity.BaseConfig;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.mh.storage.MonitorPointData;
import com.joysuch.wwyt.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.persistence.criteria.CriteriaBuilder;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BpSafeRiskPromiseJob {



    private static final Integer  STATUS_CODE_SUCCESS = 200;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private BaseConfigService baseConfigService;

    @Autowired
    private BpRiskCompanyService bpRiskCompanyService;

    @Scheduled(cron = "0 59 09 * * ?")
    public void sendCompanyPromise(){

        BaseConfig senderOpenConfig = baseConfigService.getBaseConfigFromRedis(SyncConstants.API_SAFE_RISK_PROMISE_SENDER_OPEN);
        BaseConfig passwordConfig = baseConfigService.getBaseConfigFromRedis(SyncConstants.API_SAFE_RISK_PROMISE_SENDER_PASSWORD);
        BaseConfig orgCodeConfig = baseConfigService.getBaseConfigFromRedis(SyncConstants.API_SAFE_RISK_PROMISE_SENDER_ORGCODE);
        BaseConfig companyKeyConfig = baseConfigService.getBaseConfigFromRedis(SyncConstants.API_SAFE_RISK_PROMISE_SENDER_COMPANYKEY);
        BaseConfig tenentRequestUrlConfig = baseConfigService.getBaseConfigFromRedis(SyncConstants.API_SAFE_RISK_TENENTCODE_REQUEST);
        BaseConfig promiseSendUrlConfig = baseConfigService.getBaseConfigFromRedis(SyncConstants.API_SAFE_RISK_PROMISE_SENDER_URL);

        if( senderOpenConfig== null  || "false".equalsIgnoreCase(senderOpenConfig.getValue().trim())
                || orgCodeConfig == null || "false".equalsIgnoreCase(orgCodeConfig.getValue().trim())){
            log.info("公司级风险承诺公告发布上传关闭或未配置发布公司 org Code。");
            return;
        }

        String[] passwords = passwordConfig.getValue().split(";");
        String[] orgCodes = orgCodeConfig.getValue().split(";");
        String[] companyKeys = companyKeyConfig.getValue().split(";");
        String companyName = "";
        Map<String, BpCompany> dataMap = bpRiskCompanyService.getAnnounceMsg();
        for(int i=0;i<orgCodes.length;i++){
            try {
                BpCompany bpCompany = dataMap.get(orgCodes[i]);
                if(bpCompany == null){
                    log.info("... safe risk : 当前公司没有生成承诺公告： orgCode={} ", orgCodes[i]);
                    continue;
                }
                companyName = bpCompany.getReleaseCompany();
                APILoginBean loginBean = new APILoginBean();
                loginBean.setUsername(companyName);
                loginBean.setPassword(passwords[i]);
                log.info("... safe risk : request send out for the access code for company {} ", companyName);
                APIResponseBean response = restTemplate.postForObject(tenentRequestUrlConfig.getValue(),loginBean,APIResponseBean.class);
                log.info("... safe risk : get response for the access code for company {}: response= {}", companyName, response == null ? "" : response.toString());
                if(response.getStatusCode() != 200){
                    log.warn("... safe risk : Can't get access code for company {}, will not send out safe risk promise content .", companyName);
                    continue;
                }
                //用公司名称与账户登录获取 验证Code
                JsonObject jsonBoardcast = formatBoardcast(bpCompany, companyKeys[i], companyName);
                HttpHeaders header = new HttpHeaders();
                header.setContentType(MediaType.APPLICATION_JSON);
                header.set("code",response.getMessage());
                //HttpEntity
                HttpEntity<String> requestEntity = new HttpEntity<String>(jsonBoardcast.toString(), header);
                //post
                log.info("... safe risk : send out promise for company {}: content={} ", companyName, jsonBoardcast.toString());
                ResponseEntity<APIResponseBean> responseEntity = restTemplate.postForEntity(promiseSendUrlConfig.getValue(), requestEntity, APIResponseBean.class);
                log.info("... safe risk : send out promise for company {}: response={} ", companyName,
                        (responseEntity == null|| requestEntity.getBody() == null )? "" : responseEntity.getBody().toString());
            }catch (Exception e){
                log.error("...safe risk : 发送公司承诺公告失败 company=" + companyName, e);
            }
        }

    }


    private JsonObject formatBoardcast(BpCompany bpCompany, String companyKey, String companyName){
        JsonObject jsonBoardcast = new JsonObject();
        jsonBoardcast.addProperty("CorpKey",companyKey);
        jsonBoardcast.addProperty("CorpName",companyName);

        //生产装置套数

        jsonBoardcast.addProperty("UNITS_NUMBER",bpCompany.getDeviceSum());
        //运行套数
        jsonBoardcast.addProperty("RUN_NUMBER",bpCompany.getDeviceExecuteSum());
        //停运套数
        jsonBoardcast.addProperty("PARK_NUMBER ",bpCompany.getDeviceRepairSum());
        //检维修作业
        jsonBoardcast.addProperty("INSPECTION_NUMBER ",bpCompany.getDeviceRepairSum());

        //特殊作业处理
        List<BpTeamSpecialBean> specialWorkList = JSON.parseArray(bpCompany.getSpecialWork(), BpTeamSpecialBean.class);
        Map<String, Integer> workMap  = new HashMap<>();
        if(specialWorkList != null){
            workMap =specialWorkList.stream().collect(Collectors.toMap(BpTeamSpecialBean::getSpecialWorkName,BpTeamSpecialBean::getSum));
        }
        // 初始化默认0
        for(int i=1;i< SafetyRiskWorkTypes.values().length;i++){
            if(!workMap.containsKey(SafetyRiskWorkTypes.findNameById(i))){
                workMap.put(SafetyRiskWorkTypes.findNameById(i),0) ;
            }
        }
        jsonBoardcast.addProperty("ROADWORK_NUMBER",workMap.get(SafetyRiskWorkTypes.DUAN_LU.getName()));
        jsonBoardcast.addProperty("SOILWORK_NUMBER",workMap.get(SafetyRiskWorkTypes.DONG_TU.getName()));
        int highWork = workMap.get(SafetyRiskWorkTypes.GAO_CHU_0.getName())
                + workMap.get(SafetyRiskWorkTypes.GAO_CHU_1.getName())
                + workMap.get(SafetyRiskWorkTypes.GAO_CHU_2.getName())
                + workMap.get(SafetyRiskWorkTypes.GAO_CHU_3.getName());
        jsonBoardcast.addProperty("HIGHWORK_NUMBER",highWork);
        jsonBoardcast.addProperty("ELECTRICITYWORK_NUMBER",workMap.get(SafetyRiskWorkTypes.LIN_SHI_YONG_DIAN.getName()));
        jsonBoardcast.addProperty("LIFTINGWORK_NUMBER",workMap.get(SafetyRiskWorkTypes.DIAO_ZHUANG.getName()));
        jsonBoardcast.addProperty("BLINDPLATE_NUMBER",workMap.get(SafetyRiskWorkTypes.MANG_BAN_CHOU_DU.getName()));
        jsonBoardcast.addProperty("FIRE2_NUMBER ",workMap.get(SafetyRiskWorkTypes.DONG_HUO_2.getName()));
        jsonBoardcast.addProperty("FIRE1_NUMBER ",workMap.get(SafetyRiskWorkTypes.DONG_HUO_1.getName()));
        jsonBoardcast.addProperty("FIRES_NUMBER ",workMap.get(SafetyRiskWorkTypes.DONG_HUO_0.getName()));
        jsonBoardcast.addProperty("SPACEWORK_NUMBER ",workMap.get(SafetyRiskWorkTypes.SHOU_XIAN_KONG_JIAN.getName()));

        //是否有承包商作业
        jsonBoardcast.addProperty("CONTRACTOR ",1);
        //是否处于试生产期
        jsonBoardcast.addProperty("BTRIAL_PRODUCTION ","是".equals(bpCompany.getPreProduceOrNot())? 1: 0);
        //开停车
        jsonBoardcast.addProperty("OPEN_PARKING ", "是".equals(bpCompany.getDriveOrNot())? 1: 0);
        //是否开展中（扩）试
        jsonBoardcast.addProperty("TEST",0);
        //有无重大隐患: 与是否安全状态取反
        jsonBoardcast.addProperty("M_HAZARDS ",0);
        //风险级别
        jsonBoardcast.addProperty("RISK_GRADE ","2");
        //日期
        jsonBoardcast.addProperty("COMMITE_DATE", SimpleDateFormatCache.getYmd().format(new Date()));
        //责任人
        jsonBoardcast.addProperty("COMMITMENT", bpCompany.getReleaseUserName());

        return jsonBoardcast;
    }



}
